<template>
  <el-dialog v-model="addOrEditVisible" title="管理员管理" :before-close="closeEditDialog" width="60%">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="160px" class="demo-ruleForm"
      :size="formSize" status-icon>
      <el-row>
        <el-col :span="24">
          <el-form-item label="管理员名称" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="头像" prop="fileName">
            <form-up-load-image @uploadImageCallback="uploadImageCallback" :image-url="ruleForm.url"></form-up-load-image>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="ruleForm.phone" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="Email" prop="email">
            <el-input v-model="ruleForm.email" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="机构" prop="deptId">
            <el-cascader style="width: 100%" v-model="ruleForm.deptId" :options="deptTreeData" :props="deptProps"
              :show-all-levels="true" placeholder="请选择机构" @change="deptTreeChange" filterable clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="角色" prop="roleIds">
            <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择角色">
              <el-option v-for="item in roleData" :label="item.roleName" :value=item.id></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="状态" prop="statusFlag">
            <el-radio-group v-model="ruleForm.statusFlag" class="ml-4">
              <el-radio v-for="(status,index) in STATUS_LIST" :label=status.label size="large">{{status.text}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeEditDialog">关闭</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRef } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from "element-plus";
import { Admin } from "@/apis/model/system/AdminModel";
import { insertAdmin, updateAdmin } from "@/apis/http/system/AdminHttp";
import { Permit } from "@/apis/model/system/PermitModel";
import { deptLoop } from "@/apis/http/system/DeptHttp";
import { Dept } from "@/apis/model/system/DeptModel";
import { rolePage } from "@/apis/http/system/RoleHttp";
import { Params } from "@/apis/model/common/common.interfaces";
import { Role } from "@/apis/model/system/RoleModel";
import {STATUS_LIST} from '@/util/common.util';
import {File} from "@/apis/model/system/FileModel";
import FormUpLoadImage from "@/components/form/FormUpLoadImage.vue";

interface Prop {
  addOrEditVisible: boolean,
  ruleForm: Admin,
  addDataType: string,
  multiple: false,
  checkStrictly: true,
}

// 刷新list页面
const refushList = ref(false);

// 传递过来的参数
const props = defineProps<Prop>();

const emit = defineEmits(["closeEditDialog"]);

// 机构
const deptTreeData: any = ref<Array<Dept>>([])
const roleData = ref<Array<Role>>([])
// 关闭按钮
const closeEditDialog = () => {
  emit("closeEditDialog", {
    addOrEditVisible: !props.addOrEditVisible,
    refushList: refushList.value
  })
}

const deptProps = {
  expandTrigger: 'click',
  multiple: false,
  value: 'id',
  label: 'deptName',
  children: 'children',
  checkStrictly: true,
}
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入管理员名称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' }
  ],
  deptId: [
    { required: true, message: '请输入机构', trigger: 'blur' }
  ],
  roleIds: [
    { required: true, message: '请选择角色', trigger: 'blur' }
  ],
  statusFlag: [
    { required: true, message: '请选择状态', trigger: 'blur' }
  ],
})


/**
 * 上传图片回调
 */
const uploadImageCallback = (e: File) => {
  props.ruleForm.url = e.url;
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 新增
      if (props.addDataType === 'add') {
        insertAdmin(props.ruleForm).then(res => {
          const code = res.code;
          const message: string = res.message;
          const data = res.data;
          if (code == 200) {
            ElMessage({
              message: '添加数据成功',
              type: 'success',
            })
            refushList.value = true
            closeEditDialog()
          }
        })
      } else if (props.addDataType === 'edit') {
        updateAdmin(props.ruleForm).then(res => {
          const code = res.code;
          const message: string = res.message;
          const data = res.data;
          if (code == 200) {
            ElMessage({
              message: '更新数据成功',
              type: 'success',
            })
            refushList.value = true
            closeEditDialog()
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

/**
 * 获取数据
 * @param value json类型的数据
 */
const deptTreeChange = (value: any) => {
  if (value == null) {
    props.ruleForm.deptId = -1;
    return;
  }

  for (var i = 0; i < 10; i++) {
    if (value[i] == undefined) {
      props.ruleForm.deptId = value[i - 1]
      break;
    }
  }
}

const initDept = async () => {
  await deptLoop().then(res => {
    const code = res.code
    const message = res.message
    const data = res.data as Array<Dept>
    if (code == 200) {
      deptTreeData.value = data;
    }
  });
}

const initRole = async () => {
  let params: Params = reactive({
    current: 1,
    size: 1000,
    search: '',
    entity: {} as Role
  })
  rolePage(params).then(res => {
    const code = res.code
    const message = res.message
    const data = res.data
    if (code == 200) {
      roleData.value = data.list
    }
  })
}

onMounted(() => {
  initDept();
  initRole();
})


</script>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

::v-deep .el-cascader__tags .el-cascader__search-input {
  min-width: 0;
}

.el-select {
  width: 100%;
}
</style>
